package cn.edu.nit.sys.controller;

import cn.edu.nit.sys.config.OperationAnnotation;
import cn.edu.nit.sys.dto.RoleDTO;
import cn.edu.nit.sys.entity.Role;
import cn.edu.nit.sys.service.RoleService;
import cn.edu.nit.sys.utils.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author xiaobai
 * @Date 2022/9/4 19:42
 * @Version 1.0.0
 */
@RestController
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private RoleService roleService;

    @GetMapping
    public R getList(String name) {
        return roleService.getRoleList(name);
    }

    @PutMapping
//    @PreAuthorize("hasAuthority('ADMIN')")
    @OperationAnnotation(description = "修改角色信息", opType = "修改")
    public R updateRoleInfo(@RequestBody Role role) {
        return roleService.updateById(role) ? R.ok("修改成功") : R.error("修改失败");
    }

    @PostMapping
//    @PreAuthorize("hasAuthority('ADMIN')")
    @OperationAnnotation(description = "添加角色", opType = "添加")
    public R addRole(@RequestBody Role role) {
        return roleService.addRole(role);
    }

    @DeleteMapping("/{id}")
//    @PreAuthorize("hasAuthority('ADMIN')")
    @OperationAnnotation(description = "删除角色", opType = "删除")
    public R delRole(@PathVariable("id")Integer id) {
        return roleService.removeById(id) ? R.ok("删除成功") : R.error("删除失败");
    }

    @GetMapping("/all")
    public R getRoleOption() {
        List<Role> list = roleService.list();
        List<RoleDTO> roleDTOS = new ArrayList<>();
        for (Role role : list) {
            RoleDTO roleDTO = new RoleDTO();
            BeanUtils.copyProperties(role, roleDTO);
            roleDTOS.add(roleDTO);
        }
        return R.ok(roleDTOS);
    }
}
